﻿using System.Web;
using System.Web.Routing;
using System.Web.Mvc;
using System;
using System.Configuration;
using System.Web.Configuration;
using Castle.Core.Configuration;
using System.Web.Optimization;

namespace Inovout.Web
{
    public class WebApplication : HttpApplication, IApplication
    {
        private bool isDebug;
        public bool IsDebug
        {
            get { return isDebug; }
        }
        public string Title
        {
            get { return applicationWrapper.Title; }
        }
        protected ApplicationWrapper applicationWrapper;
        protected void Application_Start(object sender, EventArgs e)
        {
            Run();
        }
        public IConfiguration ApplicationConfiguration
        {
            get { return applicationWrapper.ApplicationConfiguration; }
        }
        protected string path;
        public string Path
        {
            get { return path; }
        }
        protected WebApplication()
        {
            Type webApplicationType = this.GetType();
            while (!webApplicationType.Equals(typeof(WebApplication)))
            {
                this.name = webApplicationType.Assembly.GetName().Name;
                webApplicationType = webApplicationType.BaseType;
            }
        }
        protected WebApplication(string name)
        {
            ArgumentAssert.IsNotDefault(name, "name");
            this.name = name;
        }
        private string name;
        public string Name
        {
            get { return name; }
        }
        public virtual void Run()
        {
            path = HttpRuntime.AppDomainAppPath;
            SetIsDebug();
            applicationWrapper = new ApplicationWrapper(this);
            applicationWrapper.Initialize();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            RegisterContents(BundleTable.Bundles);

            ControllerBuilder.Current.SetControllerFactory(ComponentRegistry.Resolve<IControllerFactory>());
            ModelMetadataProviders.Current = new ModelDescriptorModelMetadataProvider();
            HtmlHelper.ClientValidationEnabled = true;
            HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
            ModelValidatorProviders.Providers.Clear();
            ModelValidatorProviders.Providers.Add(new ModelDescriptorModelValidatorProvider());
            ModelValidatorProviders.Providers.Add(new DataErrorInfoModelValidatorProvider());
            ModelValidatorProviders.Providers.Add(new ClientDataTypeModelValidatorProvider());

            InitializeBinders();
        }
        protected virtual void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
        protected virtual void RegisterContents(BundleCollection contents)
        {
            ContentResource.Load(this);
            foreach (ContentResource contentResource in ContentResource.StyleResources)
            {
                contents.Add(new StyleBundle(contentResource.Uri).Include(contentResource.IncludeContentResourceUris));
            }
            foreach (ContentResource contentResource in ContentResource.ScriptResources)
            {
                contents.Add(new ScriptBundle(contentResource.Uri).Include(contentResource.IncludeContentResourceUris));
            }
        }
        private void InitializeBinders()
        {
            ModelBinders.Binders.DefaultBinder = ComponentRegistry.Resolve<IModelBinder>();
        }
        private void SetIsDebug()
        {
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
            SystemWebSectionGroup systemWeb = config.GetSectionGroup("system.web") as SystemWebSectionGroup;
            isDebug = systemWeb.Compilation.Debug;

        }
        protected virtual void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
            //routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { id = RouteParameter.Optional }
            //);

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

        }





    }
}
